﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Monitor.Filters;
using Monitor.Models.JsonModel;
using Monitor.Repository.DataRepository.LinqModel;
using Monitor.Repository.Development;
using Monitor.Repository.UserRepository.LinqModel;
using Car = Monitor.Repository.UserRepository.LinqModel.Car;

namespace Monitor.Controllers.ApiControllers
{
    public class DetailsCarController : MainApiController
    {

        #region извлекает дерево машин
        [WebApiOutputCache(1,300)]
        public Collection<TreeElementJson> Get()
        {
            Collection<TreeElementJson> result = new Collection<TreeElementJson>();
            try
            {
                
                Task.Factory.StartNew(() =>
                                          {
                                              
                                              foreach (
                                                  CarGroup carGroup in
                                                      UserRepository.GetUser(User.Identity.Name).CarGroups)
                                              {
                                                  TreeElementJson carGroupJson = new TreeElementJson()
                                                                                     {
                                                                                         Id =
                                                                                             "tree_" +
                                                                                             carGroup.GroupCarId.
                                                                                                 ToString(),
                                                                                         ParentId =
                                                                                             (carGroup.ParentId == -1)
                                                                                                 ? "-1"
                                                                                                 : "tree_" +
                                                                                                   carGroup.ParentId.
                                                                                                       ToString(),
                                                                                         Class = carGroup.IconClass,
                                                                                         Name = carGroup.FullName
                                                                                     };
                                                  result.Add(carGroupJson);
                                                  foreach (Car car in carGroup.Cars)
                                                    //  if (userList.Contains(car.CarId))
                                                      {
                                                          TreeElementJson carJson = new TreeElementJson()
                                                                                        {
                                                                                            Id = car.CarId.ToString(),
                                                                                            ParentId = carGroupJson.Id,
                                                                                            Class = car.IconClass,
                                                                                            Name =
                                                                                                DataRepository.
                                                                                                CarRepository.GetCarById
                                                                                                (car.Fk_CarId).CarName()
                                                                                        };
                                                          result.Add(carJson);
                                                      }
                                              }
                                          })
                                          .ContinueWith(t =>
                                                              {
                                                                  if (!t.IsCompleted)
                                                                  {
                                                                      throw new Exception("Задача не выполнена");
                                                                  }
                                                              })
                                           .Wait(20000);
            }
            catch (Exception exception)
            {
                ErrorLogger.Error(this.ControllerContext, exception);
            }
            return result;
        }

        #endregion

        #region поиск среди доступных машин по имени
        [WebApiOutputCache(5,60)]
        public IEnumerable<TreeElementJson> Get(string name)
        {
            try
            {
                if (string.IsNullOrEmpty(name))
                    return Get();
                else
                {
                    name = name.ToUpper();
                    return
                        CurrentUser.Cars.Where(n => DataRepository.CarRepository.GetCarById(n.Fk_CarId).CarName().ToUpper().Contains(name)).Select(
                            n => new TreeElementJson()
                            {
                                Id =n.CarId.ToString(),
                                ParentId = "-1",
                                Class = n.IconClass,
                                Name = DataRepository.CarRepository.GetCarById(n.Fk_CarId).CarName()
                            });}
            }
            catch (Exception ex)
            {
                ErrorLogger.Error(this.ControllerContext,ex);
            }
            return null;
        }

        #endregion

        #region извлекает информацию по одной машинке
        [WebApiOutputCache(10, 5, true)]
        public CarDetails Get(Int64 id)
        {
            try
            {
                Car car = CurrentUser.Cars.FirstOrDefault(n => n.CarId == id);
                if (car!=null)
                {
                    Repository.DataRepository.LinqModel.Car carFromOra = DataRepository.CarRepository.GetCarById(car.Fk_CarId);
                    CarDetails result = new CarDetails
                                            {
                                                Id = id,
                                                SerialCarNumber = carFromOra.SerialNumber,
                                                ListMessage = new List<Int64>(),
                                                ListCompareMesure = new List<CompareMesuring>(),
                                                ListMesure = new Dictionary<Int64, CarMesure>(),
                                                CarName = carFromOra.CarName(),
                                                //демо
                                                ErrorCount = 3, //демо
                                            };
                    RegDataRow lastPosittion = DataRepository.MesuringRepository.CoordRepository.GetLastPosition(car.Fk_CarId);
                    if (lastPosittion != null)
                    {
                        result.DateReg = lastPosittion.RegDate;

                        result.CarCoord = Coord.Parce(lastPosittion.DataFromGPS.FirstOrDefault());
                        FixedDataValue fuelLevel = lastPosittion.GetMesuring(20010000007);
                        if (fuelLevel != null)
                        {
                            result.FuelLevel = Convert.ToInt32(fuelLevel.Value);
                        }
                        else
                        {
                            result.FuelLevel = -1;
                        }

                        Random random = new Random(); //демо
                        Int64[] listOfParams =
                            DataRepository.CarRepository.GetCarById(car.Fk_CarId).ListOfParam.Select(n => n.ParamId).
                                ToArray(); //Список параметров

                        for (int i = 0; i < 3; i++) //демо
                        {
                            result.ListMessage.Add(random.Next(10));
                            int a = random.Next(10*i + 10);
                            result.ListCompareMesure.Add(new CompareMesuring()
                                                             {
                                                                 InProsess = a,
                                                                 OutProsess = 10 + 10*i - a
                                                             });
                        }

                        for (Int64 i = 20010000002; i < 20010000008; i++)
                        {
                            if (listOfParams.Contains(i))
                            {
                                FixedDataValue query = lastPosittion.GetMesuring(i);
                                if (query != null)
                                    result.ListMesure.Add(i, new CarMesure()
                                                                 {
                                                                     IdMesure = i,
                                                                     NameMesure = query.Value.ToString(),
                                                                     Value = query.Classif.FullName
                                                                 });
                            }
                        }
                    }
                    return result;
                }
            }
            catch (Exception exception)
            {
                ErrorLogger.Error(this.ControllerContext,exception);
            }
            return null;
           
        }

        #endregion
        
    }
}
